import React, { Component } from 'react';
import {
  Button,
  DeviceEventEmitter,
  Dimensions,
  FlatList,
  Image,
  ImageBackground,
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  ToastAndroid,
  TouchableOpacity,
  View,
} from 'react-native';
import UserIcon from '../../compenent/UserIconList';
import UserIconList from '../../compenent/UserIconList';
import { style } from '../../../theme.js';
import { DOMAIN_URL, eventApplyList, eventDelete, eventDetail, userRead, userUnread } from '../../../util/api';
import Icon from 'react-native-vector-icons/MaterialIcons';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Dialog, Paragraph, Portal, Provider } from 'react-native-paper';
import { PAGENAME } from '../../../util/PageName';
import moment from "moment/moment";
import ListFooter from '../../compenent/ListFooter';

const { width, height } = Dimensions.get('screen');

class ActiveDetailScreen extends Component {

  constructor(props: any) {
    super(props);
    console.log('load detail ', props.route.params.data);

    this.state = {
      data: props.route.params.data,
      visible: false,
      isAdmin: false,
      applies: [],
      joinUser: [],
      unjoinUser: [],
    };
    AsyncStorage.getItem('isAdmin').then(value => {
      console.log('this.state.isAdmin', value);
      this.setState({
        isAdmin: value == 'true' ? true : false,
      });
    });
  }
  componentDidMount() {
    this.subscription = this.props.navigation.addListener('focus', () => {
      // do something
      console.log('event detail');
      this.loadDataDetail()
    });
  }

  componentWillUnmount() {
    this.subscription()
  }

  renderItem = ({ index, item }) => {
    console.log('apply item ', item);
    return <TouchableOpacity onPress={() => {
      this.props.navigation.push(PAGENAME.ACTIVE_APPLY, { action: global.ACTION.VIEW, apply: item })
    }}  >
      <View style={style.indexDataRow} key={item.id}>
        <Image
          style={{ width: 45, height: 45 }}
          source={{
            // "attachments":  "path":
            uri: `${DOMAIN_URL}${item.attachments[0]['path']}`,
          }}
        />
        <View style={style.applyInfo}>
          <Text style={style.applyTitle}>
            {item.title}
          </Text>
          <View style={{ flexDirection: 'row' }}>
            <View style={{ flexDirection: 'row' }}>
              <Text>{item.userInfo.userName}</Text>
              <Text style={{ marginLeft: 4 }}>{moment(item.createTime).format('YYYY-MM-DD hh:mm')}</Text>
            </View>
            <View>
              <Text style={[style.applyStatus, style[`applyStatus${item.approvalInfo.status}`]]}>{global.APPROVAL_STRING[item.approvalInfo.status]}</Text>
            </View>
          </View>
        </View>
      </View >
    </TouchableOpacity>

  }
  loadDataDetail = () => {
    eventDetail(this.state.data.id).then(res => {
      console.log('eventDetail ', res);
      this.setState({
        data: res.data
      })
    })
    eventApplyList(this.state.data.id, 1, 1000).then(res => {
      console.log('eventApplyList ', res);
      if (res.code == 0) {
        this.setState({
          applies: res.data
        })
      }
    })
    userUnread(this.state.data.id).then(res => {
      console.log('eventUnjoin ', res);
      this.setState({
        unjoinUser: res.data,
      })
    })
    userRead(this.state.data.id).then(res => {
      console.log('eventJoin ', res);
      this.setState({
        joinUser: res.data,
      })
    })
  }
  listHeader = () => {
    const { data } = this.state
    return <View>
      <Text style={style.pageTitle}>{data.name}</Text>
      <View style={{ flexDirection: 'row', alignItems: 'center' }}>
        <View style={{ flexDirection: 'row' }}>
          <Icon name={'grade'} size={18} color={'red'} />
          <Text style={{ color: 'rgba(255,0,0,0.5)', marginLeft: 2, fontSize: 16 }}>{data.score}</Text>
        </View>
        <View style={{ flexDirection: 'row', marginLeft: 6 }}>
          <Icon name={'access-time'} size={18} color={'red'} />
          <Text
            style={{
              color: 'rgba(255,0,0,0.5)',
              marginLeft: 2,
            }}>
            {moment(data.createTime).format('YYYY-MM-DD')}
          </Text>
          <Text>-</Text>
          <Text style={{ color: 'rgba(255,0,0,0.5)', marginLeft: 2 }}>
            {moment(data.endTime).format('YYYY-MM-DD')}
          </Text>
          {/*<Text style={{ color: 'rgba(255,0,0,0.5)', marginLeft: 2, fontSize: 16 }}>{data.endTime}</Text>*/}
        </View>
      </View>
      {this.state.isAdmin && <View style={{ flexDirection: 'row', marginTop: 8 }}>
        <View style={{ width: 50, height: 35, }}>
          <Button title={'编辑'} onPress={() => {
            this.props.navigation.push(PAGENAME.ACTIVE_EDIT, { data: data })
          }} />
        </View>
        <View style={{ width: 50, height: 35, marginLeft: 8 }}>
          <Button title={'删除'} onPress={() => {
            this.setState({
              visible: true
            })
          }} />
        </View>
      </View>}
      <Text style={{ marginVertical: 16 }}>{data.description}</Text>
      {data.imageDetails.map(img => {
        return (
          <View style={{ alignItems: 'center', margin: 4 }}>
            <Image
              style={{ width: '95%', height: 150 }}
              source={{
                uri: `${DOMAIN_URL}${img.path}`,
              }}
            />
          </View>
        );
      })}
      <View
        style={{
          justifyContent: 'center',
          alignContent: 'center',
          marginVertical: 30,
        }}>
        <View style={style.pageButton}>
          {data.available ? <Button
            title={'参加活动'}
            onPress={() => {
              this.props.navigation.push(PAGENAME.ACTIVE_APPLY, { active: data, action: global.ACTION.ADD })
            }}
          /> : <Button
            title={'活动已结束'}
            disabled={true}
            onPress={() => {
            }}
          />}
        </View>
      </View>

      {this.state.isAdmin && (
          <View>
            <Text style={style.subTitle}>参与党员</Text>
            <UserIconList users={this.state.joinUser} />
            <Text style={style.subTitle}>未参与党员</Text>
            <UserIconList users={this.state.unjoinUser} />
          </View>
      )}
      <Text style={style.subTitle}>审批列表</Text>


    </View>
  }
  listSep = () => {
    return <View style={{
      height: 1, // 分割线的高度
      width: '100%', // 分割线的宽度，这里设置为100%使其充满整个容器宽度
      backgroundColor: 'rgb(246, 150, 150)', // 分割线的颜色
      marginVertical: 6, // 分割线上下的外边距，可以根据需要调整
    }}></View>
  }
  deleteActive = () => {
    eventDelete(this.state.data.id).then(res => {
      if (res.code == 0) {
        ToastAndroid.show('删除成功', 2000)
        this.setState({
          visible: false
        })
        this.props.navigation.goBack({ refresh: true });
        // DeviceEventEmitter.emit(PAGENAME.ACTIVE, { name: 'back' });
      } else {
        ToastAndroid.show(`删除失败:${res.msg}`, 2000)
      }
    })
  }
  render() {
    return (
      <Provider>
        <View>
          <Portal>
            <Dialog visible={this.state.visible} onDismiss={() => {
              this.setState({
                visible: false
              })
            }}>
              <Dialog.Title>确认删除数据</Dialog.Title>
              <Dialog.Content>
                <Paragraph>确认删除：{this.state.data.name}</Paragraph>
              </Dialog.Content>
              <Dialog.Actions>
                <View style={{ width: 100 }}>
                  <Button title={'删除'} color={'red'} onPress={this.deleteActive} />
                </View>
                <View style={{ marginLeft: 8, width: 100 }}>
                  <Button title={'取消'} onPress={() => {
                    this.setState({
                      visible: false
                    })
                  }} />
                </View>


              </Dialog.Actions>
            </Dialog>
          </Portal>
        </View>
        <SafeAreaView style={styles.container}>
          <FlatList
            data={this.state.applies}
            renderItem={this.renderItem}
            ListHeaderComponent={this.listHeader}
            keyExtractor={item => item.id}
            // extraData={this.state.selectedId}
            ItemSeparatorComponent={this.listSep}
            ListEmptyComponent={this.emptyApply}
            ListFooterComponent={<ListFooter />}
          />
        </SafeAreaView >
      </Provider>

      // </ImageBackground>
    );
  }
  emptyApply = () => {
    return <View style={{ justifyContent: 'center', alignItems: 'center', margin: 8 }}><Text>暂无申请</Text></View>
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginHorizontal: 8,
    marginTop: 8,
  },

});

export default ActiveDetailScreen;
